import 'dart:convert';
import 'dart:ffi';
import 'dart:math';

import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/pages/client/home/service_detail.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chathouse/model/species.dart';

import '../expert_root_page.dart';
import '../home_page.dart';

// 发送付款凭证页面
class BankTransferCerSendPage extends StatefulWidget {
  Rows? row;
  String? orderId;

  BankTransferCerSendPage(this.row, this.orderId, {Key? key}) : super(key: key);

  @override
  _BankTransferInfoPageState createState() => _BankTransferInfoPageState();
}

class _BankTransferInfoPageState extends State<BankTransferCerSendPage> {
  String imageUrl = "";

  void approvalRecharge(bool isShow) {
    if (imageUrl.isEmpty) {
      return;
    }
    final map = {
      "accountNumber": SpUtil.getString(AppConstant.accountNumber),
      "bankName": SpUtil.getString(AppConstant.bankName),
      "voucherId": widget.row!.id,
      "imgPath": imageUrl,
      "tradingCode": Random().nextInt(100000),
      "money": widget.row!.moneyAmount,
      "serviceContent": "充值${widget.row!.tokenAmount}金币",
      "id": widget.row!.id,
      "incomeExpenses": "0",
      // ignore: equal_keys_in_map
      "tradingCode": widget.orderId ?? ""
    };
    Obj.showLoading();
    Apis.addApprovalRecharge(map)
        .then((value) => {
              Obj.dismissLoading(),
              if (isShow)
                {
                  showSuccessMsg(),
                }
            })
        .onError((error, stackTrace) => {Obj.dismissLoading()});
  }

  showBackMsg() {
    showDialog(
        context: context,
        barrierColor: Colors.black54,
        builder: (BuildContext context) {
          return Container(
            // color: Colors.black26,
            child: Center(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                width: 358.w,
                height: 370.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Styles.magin_40)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("訂單已生成，退出后 可通過充值記錄進入訂單 完成後續操作，是否現 在退出？",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.MID, color: Styles.c_191919)),
                    SizedBox(
                      height: 36.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.c_FF9090,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "退出",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 20.w),
                      ),
                    ).setOnClickListener(() {
                      approvalRecharge(false);
                      Future.delayed(const Duration(seconds: 1), () {
                        Get.offAll(const ExpertRootPage());
                      });
                    }),
                    SizedBox(
                      height: 16.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.c_999,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "取消",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 20.w),
                      ),
                    ).setOnClickListener(() {
                      Navigator.pop(context);
                    }),
                  ],
                ),
              ),
            ),
          );
          // );
        });
  }

  showSuccessMsg() {
    showDialog(
        context: context,
        barrierColor: Colors.black54,
        builder: (BuildContext context) {
          return Container(
            child: Center(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                width: 358.w,
                height: 310.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Styles.magin_40)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("發送成功！系統將在2-7個工作天内進行驗證，驗證 通過將自動發放代幣。 請留意提示訊息！",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.MID, color: Styles.c_191919)),
                    SizedBox(
                      height: 40.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.mainColor,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "知道了",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 24.w),
                      ),
                    ).setOnClickListener(() {
                      goDetail();
                    })
                  ],
                ),
              ),
            ),
          );
        });
  }

  goDetail() {
    if (!Get.currentRoute.contains("ExpertServiceDetailPage")) {
      Get.back();
      goDetail();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Icon(
          Icons.arrow_back_ios,
          size: 18.w,
          color: MyColors.gary_149149149,
        ).setOnClickListener(() {
          Get.back();
        }),
        title: Text(
          "充值驗證",
          textAlign: TextAlign.center,
          style:
              getTextStyle(28.sp, color: Colors.black, fontType: FontType.MID),
        ),
        actions: [
          Container(
            padding: const EdgeInsets.only(right: 12),
            child: Center(
              child: Text(
                "發送",
                textAlign: TextAlign.center,
                style: getTextStyle(20.sp,
                    color: Styles.mainColor, fontType: FontType.BOLD),
              ),
            ),
          ).setOnClickListener(() {
            approvalRecharge(true);
          })
        ],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 26.w, vertical: 20.w),
        width: double.infinity,
        child: Column(
          children: [
            Text(
              "*轉數成功後需向我們發送轉數成功截圖以便進行驗證",
              textAlign: TextAlign.left,
              style: getTextStyle(18.sp,
                  color: Styles.c_999, fontType: FontType.MID),
            ),
            SizedBox(
              height: 30.w,
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: imageUrl.isNotEmpty
                  ? ImageUtils.image(imageUrl,
                      width: 102.w,
                      height: 102.w,
                      imageType: ImageType.NETWORK,
                      radius: 12)
                  : Container(
                      width: 102.w,
                      height: 102.w,
                      decoration: BoxDecoration(
                          color: MyColors.gary_230230230,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ImageUtils.image(Res.image_pick_add,
                              width: 51.w, height: 51.w),
                          SizedBox(height: 6.w),
                          Text(
                            "選擇照片",
                            style: getTextStyle(16.sp,
                                color: MyColors.brow_25511377),
                          ),
                        ],
                      ),
                    ).setOnClickListener(() {
                      onAddImage();
                    }),
            ),
            SizedBox(
              height: 60.w,
            ),
            Text(
              "*您也可以通過以下方法向我們發送入數截圖.",
              textAlign: TextAlign.left,
              style: getTextStyle(18.sp,
                  color: Styles.c_999, fontType: FontType.MID),
            ),
            SizedBox(
              height: 20.w,
            ),
            Row(
              children: [
                ImageUtils.image(Res.expert_phone_img,
                    width: 26.w, height: 26.w),
                const SizedBox(
                  width: 6,
                ),
                Text(
                  // +852 5110 9192
                  "WhatsApp:(+852) 5110 9192",
                  textAlign: TextAlign.left,
                  style: getTextStyle(17.sp,
                      color: Styles.c_191919, fontType: FontType.BOLD),
                ),
              ],
            ),
            SizedBox(
              height: 16.w,
            ),
            Row(
              children: [
                ImageUtils.image(Res.expert_email, width: 26.w, height: 20.w),
                const SizedBox(
                  width: 6,
                ),
                Text(
                  "電子郵箱:admin@chathouse.com.hk",
                  textAlign: TextAlign.left,
                  style: getTextStyle(17.sp,
                      color: Styles.c_191919, fontType: FontType.BOLD),
                ),
              ],
            ),
            Expanded(
              child: Container(),
              flex: 1,
            ),
            Container(
              margin: EdgeInsets.only(bottom: 50.w),
              alignment: Alignment.center,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 60.w),
                decoration: BoxDecoration(
                    color: Styles.c_999,
                    borderRadius: BorderRadius.circular(20.w)),
                child: const Text(
                  "稍後自行發送",
                  style: TextStyle(
                      color: Colors.white, fontWeight: FontWeight.w600),
                ).setOnClickListener(() {
                  showBackMsg();
                }),
              ),
            )
          ],
        ),
      ),
    );
  }

  void onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
                  width: double.infinity,
                  height: 60.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            Get.back(result: 1);
          }),
          Text(
            "相機",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
            alignment: Alignment.center,
            width: double.infinity,
            height: 60.w,
          )
              .setOnClickListener(() {
            Get.back(result: 2);
          }),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if (imgData != null) {
      Obj.showLoading();
    }
    Map result;
    String? url;
    Apis.uploadFile(imgData!, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  print(imageUrl),
                  setState(() {
                    imageUrl = url!;
                  }),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }
}
